package com.shiny.concurrency4java.lock;

import com.shiny.concurrency4java.annoations.NotThreadSafe;
import com.shiny.concurrency4java.util.Constant;
import lombok.Getter;
import lombok.Setter;
import lombok.extern.slf4j.Slf4j;

import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Semaphore;

@Slf4j
@NotThreadSafe
public class VolatileExample {

    @Getter
    @Setter
    private volatile long v1 = 0L;

    private void getAndIncrement(){
        v1++;
    }

    public static void main(String[] args) throws Exception {
        VolatileExample volatileExample = new VolatileExample();
        ExecutorService executorService = Executors.newCachedThreadPool();
        final Semaphore semaphore = new Semaphore(Constant.threadTotal);
        final CountDownLatch countDownLatch = new CountDownLatch(Constant.clientTotal);
        for (int i = 0; i < Constant.clientTotal; i++) {
            executorService.execute(() -> {
                try {
                    semaphore.acquire();
                    volatileExample.getAndIncrement();
                    semaphore.release();

                } catch (Exception e) {
                    e.printStackTrace();
                }
                countDownLatch.countDown();
            });
        }
        countDownLatch.await();
        executorService.shutdown();
        log.info("volatileExamplen v1:{}",volatileExample.getV1());
    }




}
